from rest_framework import serializers

from goods.models import SKU


class CartSerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1, label="商品编号")
    count = serializers.IntegerField(min_value=1, label="商品数量")
    selected = serializers.BooleanField(default=True, required=False)  # 参数一是默认选中,参数二是可以不传

    # 多字段效验
    def validate(self, attrs):
        # 获取数据
        sku_id = attrs["sku_id"]
        count = attrs["count"]
        # 判断商品是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            raise serializers.ValidationError("商品不存在")
        # 判断count是否大于库存量
        if count > sku.stock:
            raise serializers.ValidationError("商品库存不足")

        return attrs

class CartDeleteSerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1, label="商品编号")

    # 单字段效验
    def validate(self, validate_data):
        # 获取sku_id对应的对象是否存在
        sku_id = validate_data["sku_id"]
        try:
            SKU.objects.get(id=sku_id)
        except Exception as e:
            raise serializers.ValidationError("商品不存在")

        return validate_data


